import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { title } from 'process';
import { DeepPartial, getRepository, Repository } from 'typeorm';
import  { PostsEntity } from '../entities/posts.entity';

export interface PostsRo {
  statusCode:number
  data:{
    list: PostsEntity[];
  }
  count: number;
}

// 返回修改的数据类型
export interface UpdatePostsType {
  statusCode:number
  data:{}
  msg:string
}
@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(PostsEntity)
    private readonly postsRepository: Repository<PostsEntity>,
  ) {}

  // 创建文章
  async create(post: Partial<PostsEntity>): Promise<PostsEntity> {
    const { title } = post;
    if (!title) {
      throw new HttpException('缺少文章标题', 401);
    }
    const doc = await this.postsRepository.findOne({ where: { title } });
    if (doc) {
      throw new HttpException('文章已存在', 401);
    }
    return await this.postsRepository.save(post);
  }
  
  // 获取文章列表
  async findAll(query: { [x: string]: any; pageNum?: 1; pageSize?: 10; }): Promise<PostsRo> {
    const qb =  getRepository(PostsEntity).createQueryBuilder('post');
    qb.where('1 = 1');
    //根据 创建时间排序
    qb.orderBy('post.create_time', 'DESC');
    const count = await qb.getCount();
    const { pageNum = 1, pageSize = 10, ...params } = query;
    
    qb.offset(pageSize * (pageNum - 1));
    // 分页就处理好了 NB
    const posts = await qb.getMany();
    return {statusCode:200, data:{list: posts}, count: count };
  }

  // 获取指定文章
  async findById(id:number): Promise<PostsEntity> {
    return await this.postsRepository.findOne(id);
  }

  // 更新文章
  async updateById(id:number, post: DeepPartial<PostsEntity>): Promise<PostsEntity> {
    const existPost = await this.postsRepository.findOne(id);
    if (!existPost) {
      throw new HttpException(`id为${id}的文章不存在`, 401);
    }
    const updatePost = this.postsRepository.merge(existPost, post);

    return await this.postsRepository.save(updatePost);
  }

  // 刪除文章
  async remove(id:number) {
    const existPost = await this.postsRepository.findOne(id);
    if (!existPost) {
      throw new HttpException(`id为${id}的文章不存在`, 401);
    }
    return await this.postsRepository.remove(existPost);
  }

  // 根据条件查询
  // async findPostsBySearch(query: { [x: string]: any; pageNum?: 1; pageSize?: 10; }): Promise<PostsRo> {
  async findAndCount(data:string[]):  Promise<PostsEntity> {
    // 直接使用sql 语句查询
    return await this.postsRepository.query(`select * from posts where title = "${data[0]}"`);;
  }
}

